<template>
  <basic-dialog
    title="提示"
    :width="400"
    :loading="loading"
    :visible="visible"
    top="30vh"
    @closed="handleClosed"
    @submit="handleSubmit"
  >
    <div class="mb-8">确定重置该管理员密码吗？</div>
    <el-form
      ref="formRef"
      :key="formKey"
      :rules="rules"
      :model="formState"
      require-asterisk-position="right"
    >
      <el-form-item label="密码" prop="password">
        <BasicPasswordInput
          v-model="formState.password"
          default-type="text"
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
  </basic-dialog>
</template>

<script setup lang="ts">
import type { FormInstance, FormItemRule } from 'element-plus'

import type { AdminModel } from '@/apis/model/admin'

interface IProps {
  visible: boolean
  record: AdminModel
}
interface IEmits {
  (event: 'reload'): void
  (event: 'update:visible', value: boolean): void
}

const props = defineProps<IProps>()
const emit = defineEmits<IEmits>()
const formRef = ref<FormInstance>()
const formKey = ref(Date.now())

const formState = reactive({
  password: DEFAULT_PASSWORD
})

const loading = ref(false)

const rules: Record<string, FormItemRule[]> = {
  password: [
    { required: true, message: '请输入密码' },
    {
      trigger: 'blur',
      validator: passwordValidate
    }
  ]
}

const handleClosed = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
  formRef.value?.clearValidate()
  formKey.value = Date.now()
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  loading.value = true
  try {
    await resetAdminPasswordApi({
      id: props.record?.id!,
      password: formState.password
    })
    emit('update:visible', false)
    ToastUtils.success('重置成功')
    // 重置密码成功后，重新加载列表数据,如果token失效，会自动跳转到登录页
    emit('reload')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped></style>
